package use.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadUnsafeExample {
    private int cnt = 0;
    private AtomicInteger atomicCnt = new AtomicInteger(0);

    private ReentrantLock lock = new ReentrantLock();

    //    public synchronized void add() {
    //        cnt++;
    //    }
    public void add() {
        lock.lock();
        try {
            cnt++;
        } finally {
            lock.unlock();
        }
    }

    public void atomicAdd() {
        atomicCnt.getAndAdd(1);
    }
    public AtomicInteger atomicGet() {
        return atomicCnt;
    }
    public int get() {
        return cnt;
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadUnsafeExample example = new ThreadUnsafeExample();
        final int threadCount = 1000;
        CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < threadCount; i++) {
            executorService.execute(() -> {
                example.add();
                example.atomicAdd();
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println(example.get());
        System.out.println(example.atomicGet());
    }
}
